// 违纪记录管理相关功能
const DisciplineManager = {
    // 加载宿舍楼选择框
    async loadBuildingSelect() {
        Debug.log('加载宿舍楼选择框');
        loading.show();
        try {
            const buildings = await API.buildings.getAll();
            const buildingSelect = document.getElementById('disciplineBuilding');
            
            if (!buildings || buildings.length === 0) {
                buildingSelect.innerHTML = '<option value="">暂无宿舍楼</option>';
                return;
            }

            buildingSelect.innerHTML = `
                <option value="">选择宿舍楼</option>
                ${buildings.map(building => `
                    <option value="${building.id}">${building.buildingName}</option>
                `).join('')}
            `;

            // 显示所有违纪记录
            this.loadRecords();
        } catch (error) {
            Debug.error('加载宿舍楼列表失败:', error);
            alert('加载宿舍楼列表失败: ' + error.message);
        } finally {
            loading.hide();
        }
    },

    // 加载违���记录列表
    async loadRecords() {
        loading.show();
        try {
            Debug.log('开始加载违纪记录');
            const records = await API.request('/disciplinary-records', {
                headers: {
                    'Accept': 'application/json'
                }
            });
            Debug.log('成功加载违纪记录:', records);
            const disciplineList = document.getElementById('disciplineList');
            
            if (!records || records.length === 0) {
                disciplineList.innerHTML = `
                    <div class="empty-state">
                        <p>暂无违纪记录</p>
                        <button class="btn btn-primary" onclick="DisciplineManager.showAddForm()">
                            <i class="icon add-icon"></i>添加违纪记录
                        </button>
                    </div>
                `;
                return;
            }

            disciplineList.innerHTML = records.map(record => `
                <div class="discipline-card">
                    <div class="discipline-card-header">
                        <h4>${record.student.name}</h4>
                        <div class="student-info">
                            <div>学号：${record.student.studentNumber}</div>
                            <div>宿舍：${record.student.room ? 
                                `${record.student.room.building.buildingName} ${record.student.room.roomNumber}` : 
                                '未分配'}</div>
                        </div>
                    </div>
                    <div class="discipline-card-content">
                        <div class="discipline-info">
                            <div class="discipline-time">
                                记录时间：${new Date(record.recordTime).toLocaleString()}
                            </div>
                            <div class="discipline-description">
                                ${record.description}
                            </div>
                        </div>
                    </div>
                    <div class="discipline-card-footer">
                        <button class="btn btn-danger" onclick="DisciplineManager.delete(${record.id})">
                            <i class="icon delete-icon"></i>删除
                        </button>
                    </div>
                </div>
            `).join('');
        } catch (error) {
            Debug.error('加载违纪记录失败:', error);
            document.getElementById('disciplineList').innerHTML = `
                <div class="error-state">
                    <p>加载失败: ${error.message}</p>
                    <button class="btn btn-primary" onclick="DisciplineManager.loadRecords()">重试</button>
                </div>
            `;
        } finally {
            loading.hide();
        }
    },

    // 显示添加表单
    showAddForm() {
        const form = document.getElementById('addDisciplineForm');
        form.reset();
        showModal('addDisciplineModal');
    },

    // 删除违纪记录
    async delete(id) {
        if (!confirm('确定要删除这条违纪记录吗？删除后将无法恢复。')) {
            return;
        }

        try {
            loading.show();
            await API.discipline.delete(id);
            this.loadRecords();
        } catch (error) {
            Debug.error('删除违纪记录失败:', error);
            alert('删除违纪记录失败: ' + error.message);
        } finally {
            loading.hide();
        }
    },

    // 初始化
    init() {
        Debug.log('初始化违纪记录管理');
        this.loadBuildingSelect();
        
        // 监听宿舍楼选择变化
        document.getElementById('disciplineBuilding').addEventListener('change', (e) => {
            const buildingId = e.target.value;
            if (buildingId) {
                this.loadRecordsByBuilding(buildingId);
            } else {
                this.loadRecords();
            }
        });

        // 监听学生搜索
        let searchTimeout;
        document.getElementById('studentSearch').addEventListener('input', (e) => {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(async () => {
                const searchText = e.target.value.trim();
                if (!searchText) {
                    this.loadRecords();
                    return;
                }

                try {
                    loading.show();
                    const students = await API.students.search(searchText);
                    const select = document.querySelector('#addDisciplineForm select[name="studentId"]');
                    select.innerHTML = `
                        <option value="">请选择学生</option>
                        ${students.map(student => `
                            <option value="${student.id}">
                                ${student.name} (${student.studentNumber})
                            </option>
                        `).join('')}
                    `;
                } catch (error) {
                    Debug.error('搜索学生失败:', error);
                    alert('搜索学生失败: ' + error.message);
                } finally {
                    loading.hide();
                }
            }, 300);
        });

        // 添加表单提交处理
        document.getElementById('addDisciplineForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            const record = {
                studentId: parseInt(formData.get('studentId')),
                description: formData.get('description'),
                recordTime: new Date().toISOString()
            };

            try {
                loading.show();
                await API.discipline.create(record);
                hideModal('addDisciplineModal');
                this.loadRecords();
                e.target.reset();
            } catch (error) {
                Debug.error('添加违纪记录失败:', error);
                alert('添加违纪记录失败: ' + error.message);
            } finally {
                loading.hide();
            }
        });
    }
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    DisciplineManager.init();
}); 